//
//  UIViewController+GQSemiView.m
//  ContinueEducation
//
//  Created by 迟建国 on 2018/7/10.
//  Copyright © 2018年 CE. All rights reserved.
//

#import "UIViewController+GQSemiView.h"
#import <objc/runtime.h>

@implementation UIViewController (GQSemiView)

#pragma mark - private property
- (void)setGq_backgroundView:(UIView *)gq_backgroundView{
    objc_setAssociatedObject(self, @selector(gq_backgroundView), gq_backgroundView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIView *)gq_backgroundView{
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setGq_enableBlankDismiss:(BOOL )gq_enableBlankDismiss{
    objc_setAssociatedObject(self, @selector(gq_enableBlankDismiss), @(gq_enableBlankDismiss), OBJC_ASSOCIATION_ASSIGN);
}

- (BOOL)gq_enableBlankDismiss{
    if (objc_getAssociatedObject(self, _cmd)) {
        return [objc_getAssociatedObject(self, _cmd) boolValue];
    }
    // 默认激活
    return YES;
}

-(void)gq_presentSemiView:(UIView*)alert{
    
    CGSize preSize = alert.ce_size;
    
    UIButton *bgView = [UIButton buttonWithType:UIButtonTypeCustom];
    bgView.frame = self.view.bounds;
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [bgView addTarget:self action:@selector(gq_remobgViewClick:) forControlEvents:UIControlEventTouchUpInside];
    bgView.tag = 1234567890;
    [self.view addSubview:bgView];
    
    alert.frame = CGRectMake(SCREEN_W/2, SCREEN_H/2, 0, 0);
    [bgView addSubview:alert];
    
    
    [UIView animateWithDuration:0.3 animations:^{
        alert.frame = CGRectMake(SCREEN_W/2-preSize.width/2, SCREEN_H/2-preSize.height/2, preSize.width, preSize.height);
    }];
}

- (void)gq_presentFromeBottomView:(UIView *)alert{
    
    UIButton *bgView = [UIButton buttonWithType:UIButtonTypeCustom];
    bgView.frame = self.view.bounds;
    bgView.tag = 123456789;
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [bgView addTarget:self action:@selector(gq_remobgViewClick:) forControlEvents:UIControlEventTouchUpInside];
    self.gq_backgroundView = bgView;
    [self.view addSubview:bgView];
    
    alert.top = SCREEN_H;
    [bgView addSubview:alert];
    
    self.gq_backgroundView.alpha = 0;
    [UIView animateWithDuration:0.3 animations:^{
        alert.bottom = SCREEN_H;
        self.gq_backgroundView.alpha = 1;
    }];
    objc_setAssociatedObject(self, @"gq_presentFromeBottomView", alert, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
}

-(void)gq_remobgViewClick:(UIButton *)sender
{
    if (!self.gq_enableBlankDismiss) {
        return;
    }
    [self gq_removeBgView];
    [sender removeFromSuperview];
    self.gq_enableBlankDismiss = YES;// 默认yes 每次都要重置
}

- (void)gq_removeBgView{
    __weak typeof(self) weakSelf = self;
    UIButton *bgButton = (UIButton *)[self.view viewWithTag:1234567890];
    UIButton *bgBottomButton = (UIButton *)[self.view viewWithTag:123456789];
    UIViewController *vc = objc_getAssociatedObject(self, @"gq_SemiViewController");
    UIView *view = objc_getAssociatedObject(self, @"gq_presentFromeBottomView");
    if (vc || view) {
        [UIView animateWithDuration:0.25 animations:^{
            vc.view.top = SCREEN_H;
            view.top = SCREEN_H;
            weakSelf.gq_backgroundView.alpha = 0;
        } completion:^(BOOL finished) {
            [bgButton removeFromSuperview];
            [weakSelf.gq_backgroundView removeFromSuperview];
            [vc removeFromParentViewController];
            objc_setAssociatedObject(self, @"gq_SemiViewController", nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            objc_setAssociatedObject(self, @"gq_presentFromeBottomView", nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
        }];
    }else{
        
        [UIView animateWithDuration:0.25 animations:^{
            weakSelf.gq_backgroundView.alpha = 0;
        } completion:^(BOOL finished) {
            [weakSelf.gq_backgroundView removeFromSuperview];
        }];
        [bgBottomButton removeFromSuperview];
        [bgButton removeFromSuperview];
    }
}

- (void)isClickBlankToDismiss:(BOOL)enable{
    
}

- (void)gq_presentSemiViewController:(UIViewController *)vc {
    
    UIView *alert = vc.view;
    
    UIButton *bgView = [UIButton buttonWithType:UIButtonTypeCustom];
    bgView.frame = self.view.bounds;
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.0];
    [bgView addTarget:self action:@selector(gq_remobgViewClick:) forControlEvents:UIControlEventTouchUpInside];
    bgView.tag = 1234567890;
    [self.view addSubview:bgView];
    
    alert.top = SCREEN_H;
    [bgView addSubview:alert];
    
    [self addChildViewController:vc];
    objc_setAssociatedObject(self, @"gq_SemiViewController", vc, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    
    
    [UIView animateWithDuration:0.3 animations:^{
        alert.bottom = SCREEN_H;
    }];
}

- (void)gq_presentLikeAlertView:(UIView *)view{
    
    UIButton *bgView = [UIButton buttonWithType:UIButtonTypeCustom];
    if (SCREEN_H == 568) {
        bgView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H);
    }else{
        bgView.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H);
    }
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
    [bgView addTarget:self action:@selector(gq_remobgViewClick:) forControlEvents:UIControlEventTouchUpInside];
    bgView.tag = 1234567890;
    [kKeyWindow addSubview:bgView];
    bgView.alpha = 0;
    [UIView animateWithDuration:0.25 animations:^{
        bgView.alpha = 1;
    }];
    self.gq_backgroundView = bgView;
    
    view.center = bgView.center;
    
    CAKeyframeAnimation *popAnimation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    popAnimation.duration = 0.4;
    popAnimation.values = @[[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.01f, 0.01f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(1.1f, 1.1f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9f, 0.9f, 1.0f)],
                            [NSValue valueWithCATransform3D:CATransform3DIdentity]];
    popAnimation.keyTimes = @[@0.0f, @0.5f, @0.75f, @1.0f];
    popAnimation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut],
                                     [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
//    [view.layer addAnimation:popAnimation forKey:nil];暂时禁止动画效果，
    [bgView addSubview:view];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gq_keyboardChange:) name:UIKeyboardWillChangeFrameNotification object:nil];
}

- (void)gq_keyboardChange:(NSNotification *)aNotification
{
    NSDictionary* userInfo = [aNotification userInfo];
    CGRect keyboardEndFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardY =  keyboardEndFrame.origin.y;
    
    __block UIView *targetView = self.gq_backgroundView.subviews[0];
    void (^endFrameBlock)(void) = ^{
        targetView.bottom = keyboardY==SCREEN_H? (targetView.superview.center.y+targetView.ce_height/2) :keyboardY;
    };
    int curve = [[aNotification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] intValue];
    float duration = [[aNotification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationCurve:curve];
    [UIView setAnimationDuration:duration];
    endFrameBlock();
    [UIView commitAnimations];
    
}

#pragma mark AlertController
static void* UIAlertViewKey = @"UIAlertViewKey";
- (void)setAlertViewCallBackBlock:(UIAlertViewCallBackBlock)alertViewCallBackBlock {
    
    [self willChangeValueForKey:@"callbackBlock"];
    objc_setAssociatedObject(self, &UIAlertViewKey, alertViewCallBackBlock, OBJC_ASSOCIATION_COPY);
    [self didChangeValueForKey:@"callbackBlock"];
}

- (UIAlertViewCallBackBlock)alertViewCallBackBlock {
    
    return objc_getAssociatedObject(self, &UIAlertViewKey);
}

- (void)gq_presentAlertControllerTitle:(NSString *)title message:(NSString *)message actionTitles:(NSArray *)subTitles handler:(void(^)(NSInteger index))handler {
    [self gq_presentAlertControllerStyle:YES hasCancel:NO title:title message:message actionTitles:subTitles handler:handler];
}

- (void)gq_presentAlertControllerStyle:(BOOL)alertStyle hasCancel:(BOOL)hasCancel title:(NSString *)title message:(NSString *)message actionTitles:(NSArray *)subTitles handler:(void(^)(NSInteger index))handler {
    
//    if ([UIDevice currentDevice].systemVersion.floatValue<8.0) {
//
//        if (alertStyle) {//废弃不用了
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:(id<UIAlertViewDelegate>)self cancelButtonTitle:hasCancel?@"取消":nil otherButtonTitles:nil];
//            for (NSString *subT in subTitles) {
//                [alert addButtonWithTitle:subT];
//            }
//            [alert show];
//        }else{
//            UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:title delegate:(id<UIActionSheetDelegate>)self cancelButtonTitle:hasCancel?@"取消":nil destructiveButtonTitle:nil otherButtonTitles:nil];
//            for (NSString *subT in subTitles) {
//                [sheet addButtonWithTitle:subT];
//            }
//            [sheet showInView:self.view];
//
//        }
//        self.alertViewCallBackBlock = handler;
//
//        return;
//    }
    
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:alertStyle];
    
    if (hasCancel) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            if (handler) {
                handler(subTitles.count);
            }
            
        }];
        [alert addAction:action];
    }
    
    for (NSString *subT in subTitles) {
        NSInteger index = [subTitles indexOfObject:subT];
        UIAlertAction *action = [UIAlertAction actionWithTitle:subT style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            if (handler) {
                handler(index);
            }
            
        }];
        [alert addAction:action];
    }
    [self presentViewController:alert animated:YES completion:nil];
}

//- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex{
//    if (self.alertViewCallBackBlock) {
//        self.alertViewCallBackBlock(buttonIndex);
//    }
//}
//
//- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
//    if (self.alertViewCallBackBlock) {
//        self.alertViewCallBackBlock(buttonIndex);
//    }
//}

- (void)addWaterMarkText:(NSString*)waterText WithTextColor:(UIColor*)color WithFont:(UIFont*)font WithOpacity:(float)opacity {
    //计算水印文字的宽高
    NSString *waterMark = waterText;
    CGSize textSize = [waterMark sizeWithAttributes:@{NSFontAttributeName:font}];
    CGFloat height =  [UIScreen mainScreen].bounds.size.height;
    CGFloat width =  [UIScreen mainScreen].bounds.size.width-50;
    NSInteger row = 5; //行
    NSInteger col = 3; //列
   
    for (int i = 0; i < row; i ++) {
        for (int j = 0; j < col; j ++) {
            CATextLayer *textLayer = [[CATextLayer alloc]init];
            textLayer.contentsScale = [UIScreen mainScreen].scale;//按当前屏幕分辨显示，否则会模糊
            CFStringRef fontName = (__bridge CFStringRef)font.fontName;
            CGFontRef fontRef =CGFontCreateWithFontName(fontName);
            textLayer.font = fontRef;
            textLayer.fontSize = font.pointSize;
            textLayer.foregroundColor = color.CGColor;
            textLayer.string = waterMark;
            textLayer.opacity = opacity;
            textLayer.frame = CGRectMake(12+j*width/col,  50+i*(height/5), textSize.width, textSize.height);
            //旋转文字
            textLayer.transform = CATransform3DMakeRotation(-M_PI/8, 0,0,3);
            [self.view.layer addSublayer:textLayer];
        }
    }
}
@end
